<?php

namespace app\models;

use Yii;
use yii\db\ActiveQuery;
use app\helpers\ArrayHelper;
use yii\behaviors\TimestampBehavior;
use yii\db\Exception;
use yii\db\Expression;

/**
 * This is the model class for table "{{%department}}".
 *
 * @property int $id 主键
 * @property int $group_id 组织
 * @property int $parent_id 上级
 * @property string $name 名称
 * @property string $path 层级路径
 * @property int $created_at 创建时间
 * @property int $updated_at 更新时间
 *
 * @property $parent
 * @property $group
 */
class Department extends ActiveRecord
{
    const TYPE_ORD = 1;     //  普通
    const TYPE_SALE = 2;    //  销售

    public static function getTypeMapping()
    {
        return [
            ['id' => self::TYPE_ORD, 'name' => '普通部门'],
            ['id' => self::TYPE_SALE, 'name' => '销售部门'],
        ];
    }

    public function behaviors()
    {
        return [['class' => TimestampBehavior::class]];
    }

    public function rules()
    {
        return [[['group_id', 'parent_id', 'name', 'type', 'sort', 'path'], 'safe']];
    }

    public function getGroup()
    {
        return $this->hasOne(Group::class, ['id' => 'group_id']);
    }

    /**
     * 查询组织父级
     * @return array|\yii\db\ActiveRecord|null
     */
    public function getParent()
    {
        return self::find()->where(['id' => $this->parent_id])->one();
    }

    /**
     * 下级部门统计
     * @return bool|int|string|null
     */
    public function getChildrenCount()
    {
        return $this->hasMany(Department::class, ['parent_id' => 'id'])->count('id');
    }

    /**
     * 岗位统计
     */
    public function getPositionCount()
    {
        return $this->hasMany(Position::class, ['dept_id' => 'id'])->count('id');
    }

    public function afterSave($insert, $changedAttributes)
    {
        if ($insert) {
            $this->path = $this->parent_id ? $this->getParent()->path . '_' . $this->id : $this->id;
            $this->save(false);
        }
    }

    public static function tableName()
    {
        return '{{%department}}';
    }

    /**
     * 查询某组织下所有部门
     * @param $groupId
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getListByGroupId($groupId)
    {
        $query = self::find();
        $query->select(['id', 'parent_id AS parentId', 'name']);
        $query->where(['group_id' => $groupId]);
        $query->asArray();
        return $query->all();
    }

    /**
     * 根据组织ID查询所有部门、并统计其下用户数量
     * @param $groupId
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getListWithUserCount($groupId)
    {
        // 子查询条件
        $expressionUser = new Expression('CONCAT(d.path, "%")');

        // 子查询 用户统计
        $subQuery = UserProfile::find();
        $subQuery->select('COUNT(*)');
        $subQuery->where(['like', 'u.dept_path', $expressionUser]);
        $subQuery->asArray();
        $subQuery->alias('u');

        // 部门查询
        $query = self::find();
        $query->select(['id', 'parent_id AS parentId','group_id AS groupId', 'name', 'count' => $subQuery]);
        $query->where(['group_id' => $groupId]);
        $query->asArray()->alias('d');
        return $query->all();
    }
}
